package com.letv.android.client.episode.widget;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.letv.android.client.episode.utils.EpisodeUtils;
import com.letv.android.client.widget.LetvImageView;
import com.letv.android.young.client.R;
import com.letv.core.bean.AlbumNew;
import com.letv.core.bean.CmsBean;
import com.letv.core.bean.RecommendBean;
import com.letv.core.bean.RelateBean;
import com.letv.core.bean.RelateSetBean;
import com.letv.core.bean.VideoBean;
import com.letv.core.bean.VideoRelatedListBean;
import com.letv.core.download.image.ImageDownloader;
import com.letv.core.utils.LogInfo;
//import com.letv.download.bean.DownloadVideo;
//import com.letv.download.manager.DownloadManager;

/**
 * 相关tab listview item 
 * @author yanjuli
 *
 */
public class RelateItem extends RelativeLayout{

	private static final String TAG = RelateItem.class.getSimpleName();
	private Context mContext;
	
	public RelateItem(Context context) {
		super(context);
	}

	public RelateItem(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		mContext = context;
	}

	public RelateItem(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
	}
	
	private LetvImageView image;
	private TextView update;
	private TextView title, actor; //演员
	private TextView score;
	private TextView directory; //导演
	private TextView playCount;
	private View recommendViewIcon; //热门icon
	private TextView downloadState; //下载状态
	
	private RelateSetBean mRelatedBean;
	
	private VideoBean mTabVideoInfoBean;
	
	private TextView movieType;
	
	@Override
	protected void onFinishInflate() {
		super.onFinishInflate();
		actor = (TextView) findViewById(R.id.half_play_relate_actor);
		image = (LetvImageView) findViewById(R.id.half_play_relate_image);
		update = (TextView) findViewById(R.id.half_play_relate_update);
		title = (TextView) findViewById(R.id.half_play_relate_title);
		score = (TextView) findViewById(R.id.half_play_relate_score);
		directory = (TextView) findViewById(R.id.half_play_relate_info);
		playCount = (TextView) findViewById(R.id.half_play_relate_info_playnum);
		recommendViewIcon = findViewById(R.id.recommend_view_icon);
		movieType = (TextView)findViewById(R.id.half_play_relate_movie_type);
		downloadState = (TextView) findViewById(R.id.half_download_state_text_view);
	}
	
	private boolean isSelfVideoVideEqual(long curID){
		boolean isEqual = false;
		if (mTabVideoInfoBean!= null && 0 != mTabVideoInfoBean.getId() && curID == mTabVideoInfoBean.getId()) {
			isEqual = true;
		}
		return isEqual;
	}
	
	private boolean isRectVideoEqual(long curID){
		boolean isEqual = false;
		if (mRelatedBean != null && mRelatedBean.rect != null
				&& mRelatedBean.rect.id != 0
				&& mRelatedBean.rect.id == curID){
			isEqual = true;
		}
		return isEqual;
	}
	
	public void setItemIsSelect(long curID){
		if (mRelatedBean == null){
			LogInfo.log(TAG, "mRelatedBean == null !!! ");
			return;
		}
		
    	if (isRectVideoEqual(curID) || isSelfVideoVideEqual(curID)){
    		title.setTextColor(mContext.getResources().getColor(R.color.letv_color_ffffffff));
    		directory.setTextColor(mContext.getResources().getColor(R.color.letv_color_ffffffff));
            actor.setTextColor(mContext.getResources().getColor(R.color.letv_color_ffffffff));
            if (playCount.getVisibility() == View.VISIBLE) {
	            Drawable drawable = mContext.getResources().getDrawable(R.drawable.letv_playnum_select);
	            drawable.setBounds(0, 0, 16, 16);
				playCount.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
				playCount.setCompoundDrawablePadding(10);
	            playCount.setTextColor(mContext.getResources().getColor(R.color.letv_color_ffffffff));
            }
            score.setTextColor(mContext.getResources().getColor(R.color.letv_color_ff00a0e9));
            setBackgroundResource(R.color.letv_color_5895ed);
        }else{
            title.setTextColor(mContext.getResources().getColor(R.color.letv_color_444444));
            directory.setTextColor(mContext.getResources().getColor(R.color.letv_color_a1a1a1));
            actor.setTextColor(mContext.getResources().getColor(R.color.letv_color_a1a1a1));
            if (playCount.getVisibility() == View.VISIBLE) {
	            Drawable drawable = mContext.getResources().getDrawable(R.drawable.letv_playnum_normal);
	            drawable.setBounds(0, 0, 16, 16);
				playCount.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
				playCount.setCompoundDrawablePadding(10);
	            playCount.setTextColor(mContext.getResources().getColor(R.color.letv_color_a1a1a1));
            }
            score.setTextColor(mContext.getResources().getColor(R.color.letv_color_ff00a0e9));
            setBackgroundResource(R.drawable.letv_half_play_relate_item_selecter);
        }
    }
	
	public void bindView(RelateSetBean relatedBean){
		mRelatedBean = relatedBean;
		initItemView();
		long vid = 0;
		if (relatedBean.type == VideoRelatedListBean.RECT_CONTENT_TYPE){
			vid = relatedBean.rect.id;
			bindView(relatedBean.rect);
		}else if (relatedBean.type == VideoRelatedListBean.RELATE_CONTENT_TYPE){
			bindView(relatedBean.relate);
		}else if (relatedBean.type == VideoRelatedListBean.CMS_CONTENT_TYPE){
			bindView(relatedBean.cms);
		}else if (relatedBean.type == VideoRelatedListBean.SELF_VIDEO_TYPE){
			vid = relatedBean.tabVideoInfoBean.getVid();
			bindView(relatedBean.tabVideoInfoBean);
		}
		showDownloadState(vid);
	}

	private void showDownloadState(long vid) {
//		DownloadVideo dbBean = DownloadManager.getDownloadedVideoData(String.valueOf(vid));
//		boolean hasDownload = (dbBean != null) && dbBean.state == DownloadVideo.DownloadState.FINISHED_STATE;
//		downloadState.setVisibility(hasDownload ? VISIBLE : GONE);
	}
	
	private void bindView(VideoBean tabVideoInfoBean){
		if (tabVideoInfoBean == null){
			return;
		}
		mTabVideoInfoBean = tabVideoInfoBean;
		
		title.setText(tabVideoInfoBean.getNameCn());
		
		setCommonView("", tabVideoInfoBean.getPlayCount() + "", "",
				tabVideoInfoBean.getPic320(), tabVideoInfoBean.getEpisode(), "",
				tabVideoInfoBean.getType()+"", tabVideoInfoBean.getDuration()+"", 
				tabVideoInfoBean.getCornerMark() + "", tabVideoInfoBean.getCid());
		
		setShowByCid(tabVideoInfoBean.getCid() + "", "", "",
				tabVideoInfoBean.getSinger(), tabVideoInfoBean.getDuration()
						+ "", tabVideoInfoBean.getType() + "",
				tabVideoInfoBean.getVideoType(), tabVideoInfoBean.getArea(),
				tabVideoInfoBean.getReleaseDate(),
				tabVideoInfoBean.getSubCategory(), tabVideoInfoBean.getStyle(),
				tabVideoInfoBean.getSubTitle(), tabVideoInfoBean.getScore(), "", 
				tabVideoInfoBean.getGuest(), tabVideoInfoBean.getCornerMark());
	}
	
	private void bindView(CmsBean cms) {
		if (cms == null) {
			return;
		}
		
		recommendViewIcon.setVisibility(View.VISIBLE);
		
		image.setImageResource(R.drawable.letv_poster_defualt_pic);
		ImageDownloader.getInstance(mContext).download(image, cms.getMobilePic());
		
		if (!TextUtils.isEmpty(cms.getSubTitle())){
			directory.setVisibility(View.VISIBLE);
			setTextViewSingleLine(title);
			directory.setText(cms.getSubTitle());
		}else{
			directory.setVisibility(View.GONE);
			setTextView2Line(title);
			title.setMaxLines(2);
		}
		title.setText(cms.getNameCn());
		
		update.setVisibility(View.GONE);
		score.setVisibility(View.GONE);
		actor.setVisibility(View.GONE);
		playCount.setVisibility(View.GONE);
		movieType.setVisibility(View.GONE);

	}
	
	/**
	 * 猜你喜欢
	 * @param rect
	 */
	private void bindView(RecommendBean rect){
		if (rect == null){
			return;
		}
		
		title.setText(getTitle(rect));
		
		setCommonView(rect.score, rect.playCount, String.valueOf(rect.nowEpisodes),
				rect.pic320, String.valueOf(rect.episode), String.valueOf(rect.isEnd),
				String.valueOf(rect.type), rect.duration, rect.cornerMark, rect.cid);
		
		setShowByCid(String.valueOf(rect.cid), rect.director, rect.starring,
				rect.singer, rect.duration, String.valueOf(rect.type),
				rect.videoType, rect.dataArea, rect.releaseDate,
				rect.subCategory, rect.style, rect.subname, rect.score,
				rect.pidsubtitle, rect.guest, rect.cornerMark);
	}
	
	/**
	 * 相关系列
	 * @param relate
	 */
	private void bindView(RelateBean relate){
		if (relate == null){
			return;
		}
		
		title.setText(relate.nameCn);
		
		String picUrl = "";
		if (relate.picCollections != null){
			picUrl = relate.picCollections.pic320;
		}
		
		setCommonView(relate.score, relate.playCount, relate.nowEpisodes,
				picUrl, relate.episode, relate.isEnd, relate.type,
				relate.duration, relate.cornerMark, Integer.valueOf(relate.cid));
		
		setShowByCid(relate.cid, relate.directory, relate.starring, null,
				relate.duration, relate.type, relate.albumTypeKey, relate.area,
				relate.releaseDate, relate.subCategory, relate.style,
				relate.subTitle, relate.score, relate.pidsubtitle, "",
				relate.cornerMark);
	}
	
	private void setUpdateViewDuration(String duration){
		if (!TextUtils.isEmpty(duration) && !"0".equals(duration)){
            update.setVisibility(View.VISIBLE);
            long d = 0;
            try{
            	d = Long.parseLong(duration);
            }catch(Exception e){
            	e.printStackTrace();
            }
            update.setText(EpisodeUtils.stringForTimeNoHour(d * 1000));
            update.setVisibility(View.VISIBLE);
        }else{
            update.setVisibility(View.GONE);
        }
	}
	
	private void setCommonView(String scoreStr, String playCountStr, String nowEpisodes, String pic, String episode, String isEnd, String type, String duration, String cornerMark, int cid){
		image.setImageResource(R.drawable.letv_poster_defualt_pic);
		ImageDownloader.getInstance(mContext).download(image, pic);
		
		if (!TextUtils.isEmpty(scoreStr) && !"0".equals(scoreStr)){
			score.setVisibility(View.VISIBLE);
			score.setText(scoreStr + "分");
		}else{
			score.setVisibility(View.GONE);
		}
		
		if (!TextUtils.isEmpty(playCountStr) && !"0".equals(playCountStr)) {
			playCount.setVisibility(View.VISIBLE);
			Drawable drawable = mContext.getResources().getDrawable(
					R.drawable.letv_playnum_select);
			drawable.setBounds(0, 0, 16, 16);
			playCount.setCompoundDrawablesWithIntrinsicBounds(drawable, null,
					null, null);
			playCount.setCompoundDrawablePadding(7);
			playCount.setTextColor(mContext.getResources().getColor(
					R.color.letv_color_ffffffff));

			long count = EpisodeUtils.stringToLong2(playCountStr.trim());

		//	playCount.setText(EpisodeUtils.getString(R.string.detail_half_player_relate_play_count, EpisodeUtils.getPlayCountsToStr(count)));
		}else{
			playCount.setVisibility(View.GONE);
		}
		
		/*
		 * 类型转换
		 */
		int nEpisodeNum = 0;
    	if (!TextUtils.isEmpty(episode) && TextUtils.isDigitsOnly(episode)) {
    		nEpisodeNum = Integer.valueOf(episode);
    	}
    	
    	int nNowEpisodes = 0;
    	if (!TextUtils.isEmpty(nowEpisodes) && TextUtils.isDigitsOnly(nowEpisodes)) {
    		nNowEpisodes = Integer.valueOf(nowEpisodes);
    	}
    	
		/*
		 * 显示图片右下角更新文案
		 * type: 1 专辑 3：视频
		 */
		if (type.equals("1")) {
		    // 已完结
		    if (isEnd.equals("1")) {		    	
		        if (nEpisodeNum > 0) {
		            // 综艺更新到期数
		            if (cid == AlbumNew.Channel.TYPE_TVSHOW) {
		                update.setText(mContext.getResources().getString(R.string.detailplay_half_week_update_over, episode));
		            }
		            else {
		                update.setText(mContext.getResources().getString(R.string.detailplay_half_episode_over, episode));
		            }
		        }
		        else {
		            update.setVisibility(View.GONE);
		        }
		    }
		    // 未完结，更新中
		    else if (isEnd.equals("0")) {
		        if (nNowEpisodes > 0) {
		         // 综艺更新到期数
		            if (cid == AlbumNew.Channel.TYPE_TVSHOW) {
		                update.setText(mContext.getResources().getString(R.string.detailplay_half_week_update_to, nowEpisodes));
		            }
		            else {
		                update.setText(mContext.getResources().getString(R.string.detailplay_half_episode_update_to, nowEpisodes));
		            }
		        }
		        else {
		            update.setVisibility(View.GONE);
		        }
		    }
		    else {
		        update.setVisibility(View.GONE);
		    }
		}
		else {
		    if (!TextUtils.isEmpty(duration) && !duration.equals("0")) {
                setUpdateViewDuration(duration);
            }
		    else if (!TextUtils.isEmpty(cornerMark)) {
	            update.setText(cornerMark);
	        } 
	        else {
	            update.setVisibility(View.GONE);
	        }
		}          
	}
	
	
	private String getTitle(RecommendBean rect) {
		if (rect == null)
			return "";

		if (rect.type == 1) {
			if (!TextUtils.isEmpty(rect.pidname)) {
				return rect.pidname;
			}
		} else if (rect.type == 3) {
			if (!TextUtils.isEmpty(rect.title)) {
				return rect.title;
			}
		}
		return rect.subname;
	}
	
	private void initItemView(){
		actor.setVisibility(View.VISIBLE);
		update.setVisibility(View.VISIBLE);
		directory.setVisibility(View.VISIBLE);
		score.setVisibility(View.VISIBLE);
		playCount.setVisibility(View.VISIBLE);
		recommendViewIcon.setVisibility(View.GONE);
		movieType.setVisibility(View.GONE);
		score.setText("");
		directory.setText("");
		playCount.setText("");
		update.setText("");
		actor.setText("");
		movieType.setText("");
	}
	
	/**
	 * 设置主演导演
	 * @param starringStr
	 * @param directoryStr
	 */
	private void setDirectoryAndStarring(String starringStr, String directoryStr){
		if (!TextUtils.isEmpty(starringStr) || !TextUtils.isEmpty(directoryStr)){
    		directory.setVisibility(View.VISIBLE);
    		actor.setVisibility(View.VISIBLE);
    		setTextViewSingleLine(title);
    		if (!TextUtils.isEmpty(directoryStr)){
    			directory.setText("导演: "+directoryStr);
    		}else{
    			directory.setVisibility(View.GONE);
    		}
    		
    		if (!TextUtils.isEmpty(starringStr)){
    			actor.setText("主演: "+starringStr);
    		}else{
    			actor.setVisibility(View.GONE);
    		}
    	}else{
    		directory.setVisibility(View.GONE);
    		actor.setVisibility(View.GONE);
    		setTextView2Line(title);
    	}
	}
	
	private void setTitle2LineShow(){
		directory.setVisibility(View.GONE);
		actor.setVisibility(View.GONE);
		setTextView2Line(title);
	}
	
	StringBuffer sbType;
	/**
	 * 设置拼接的类型
	 * @param area 地区
	 * @param releaseDate 年份
	 * @param subCategory 类型
	 */
	private void setJointTypeInfo(TextView typeTextView, String area, String releaseDate, String subCategory, String style, int cid){
		if (TextUtils.isEmpty(area)
				&& TextUtils.isEmpty(releaseDate)
				&& TextUtils.isEmpty(subCategory)) {
			typeTextView.setVisibility(View.GONE);
			return;
		}
		
		if (sbType == null){
			sbType = new StringBuffer();
		}else{
			if(sbType.length() > 0){
				sbType.delete(0, sbType.length());
			}
		}
		
		sbType = sbType.append("类型: ");
		
		if (!TextUtils.isEmpty(releaseDate) && releaseDate.indexOf("-") != -1){
			releaseDate = releaseDate.substring(0, releaseDate.indexOf("-"));
		}
		
		String typeStr[] = new String[]{area, releaseDate, subCategory};
		boolean isFirst = false;
		
		for (int i = 0; i < typeStr.length; i++){
			if (!TextUtils.isEmpty(typeStr[i])){
				if (isFirst){
					sbType = sbType.append(", ");
				}
				sbType = sbType.append(typeStr[i]);
				isFirst = true;
			}
		}

		if (AlbumNew.Channel.TYPE_MUSIC == cid && !TextUtils.isEmpty(style.trim())){
			if (isFirst){
				sbType = sbType.append(", ");
			}
			sbType.append(style); 
		}
		typeTextView.setVisibility(View.VISIBLE);
		typeTextView.setText(sbType.toString());
	}
	
	/**
	 * 
	 * @param directoryStr 导演
	 * @param starringStr 演员
	 * @param singer 歌手
	 */
	private void setShowByCid(String cidStr, String directoryStr,
			String starringStr, String singer, String duration, String type,
			String videoType, String area, String releaseDate,
			String subCategory, String style,String subtitle, String scoreStr, String pidsubtitle, String guest, String cornerMark){
		int cid = 0;
		try{
			cid = Integer.parseInt(cidStr);
		}catch(Exception e){
			e.printStackTrace();
		}
		
		/**
		 * 评分 只有电影才有 
		 */
		score.setVisibility(View.GONE);
		
		/**
         * 正片的猜你喜欢需要细致区分
         * 图片右下角显示更新多少集
         * **/
        switch (cid){
            case AlbumNew.Channel.TYPE_TV: // 电视剧
            case AlbumNew.Channel.TYPE_CARTOON: //动漫
            	LogInfo.log("TYPE_MUSIC", "recommendPlayerLibs.TYPE_CARTOON ");
            	if ("1".equals(type)){ // 专辑 多少集
            		if (AlbumNew.Channel.TYPE_TV == cid){
                		setDirectoryAndStarring(starringStr, directoryStr);
                	}else if (AlbumNew.Channel.TYPE_CARTOON == cid){
                		if (!TextUtils.isEmpty(subtitle)){
                			directory.setText(subtitle);
                		}else{
                			directory.setVisibility(View.GONE);
                		}
                		setJointTypeInfo(actor, area, releaseDate, subCategory, style, cid);
                	}
        		}else{ //视频 显示时间
        			setTitle2LineShow();
        		}
            	break;
            case AlbumNew.Channel.TYPE_TVSHOW: // 综艺
            	LogInfo.log("TYPE_MUSIC", "recommendPlayerLibs.TYPE_TVSHOW ");
            	//正片专辑显示更新至X期/X期全;
            	//非正片专辑不显示
            	if ("1".equals(type)){ // 专辑 多少集
            		//正片专辑显示更新至X期/X期全;
                	//非正片专辑不显示
//            		if (!"180001".equals(videoType)){
//            			update.setVisibility(View.GONE);
//            		}
        			
            		if (!TextUtils.isEmpty(pidsubtitle)){
            			directory.setText(pidsubtitle);
            			actor.setVisibility(View.GONE);
            			setTextView2Line(directory);
            			setTextViewSingleLine(title);
            		}else{
            			setTitle2LineShow();
            		}
            		
        		}else { //视频 显示时间
        			setTitle2LineShow();
        			
        			if (!TextUtils.isEmpty(guest)){
        				directory.setText("嘉宾: " + guest);
        			}
        		}
            	break;
            	
           case AlbumNew.Channel.TYPE_MOVIE: //电影
        	   if ("1".equals(type)){ // 专辑 
        		   setDirectoryAndStarring(starringStr, directoryStr);
        		   setJointTypeInfo(movieType, area, releaseDate, subCategory, style, cid);
        		   score.setVisibility(View.GONE);
        		   playCount.setVisibility(View.GONE);
        		   
        		   if (!TextUtils.isEmpty(scoreStr) && !"0".equals(scoreStr)){
        			   update.setText(scoreStr + "分");
        		   }else{
        			   update.setVisibility(View.GONE);
        		   }
        	   }else{//视频
        		   setTitle2LineShow();
        	   }
        	   break;
        	   //娱乐、体育、风尚、NBA、热点、
            case AlbumNew.Channel.TYPE_JOY://娱乐
            case AlbumNew.Channel.TYPE_PE: //体育
            case AlbumNew.Channel.TYPE_NBA: //NBA
            case AlbumNew.Channel.TYPE_FASHION: //风尚
            case AlbumNew.Channel.TYPE_HOT: //热点
            	if ("3".equals(type)){ //视频
            		setTitle2LineShow();
            		directory.setVisibility(View.GONE);
            		actor.setVisibility(View.GONE);
            	}else{
            		setTitle2LineShow();
            		if (!TextUtils.isEmpty(subtitle)){
            			directory.setText(subtitle);
            			directory.setVisibility(View.VISIBLE);
            			actor.setVisibility(View.GONE);
            		}
            		update.setVisibility(View.GONE);
            	}
            	break;
            case AlbumNew.Channel.TYPE_MUSIC: //音乐
                LogInfo.log("TYPE_MUSIC", "recommendPlayerLibs.singer : " + singer);
                if ("3".equals(type)){ //视频
            		if (!TextUtils.isEmpty(singer)) {
            			directory.setSingleLine(true);
            			directory.setEllipsize(TextUtils.TruncateAt.END);
            			directory.setText("音乐人: " + singer);
            			actor.setVisibility(View.GONE);
            		} else {
            			directory.setVisibility(View.GONE);
            		}
            		
            		setJointTypeInfo(actor, area, releaseDate, subCategory, style, cid);
            	}else{
            		actor.setVisibility(View.GONE);
            		update.setVisibility(View.GONE);
            		setTitle2LineShow();
            		if (!TextUtils.isEmpty(singer)) {
            			directory.setSingleLine(true);
            			directory.setEllipsize(TextUtils.TruncateAt.END);
            			directory.setText("音乐人: " + singer);
            			actor.setVisibility(View.GONE);
            		} else {
            			directory.setVisibility(View.GONE);
            		}
            	}
                break;
            default:
            	LogInfo.log("TYPE_MUSIC", "recommendPlayerLibs.default ");
            	
            	if ("3".equals(type)){ //视频
            		setTitle2LineShow();
            		setJointTypeInfo(directory, area, releaseDate, subCategory, style, cid);
            	}else{
            		setTitle2LineShow();
            		if (!TextUtils.isEmpty(subtitle)){
            			directory.setText(subtitle);
            			directory.setVisibility(View.VISIBLE);
            			actor.setVisibility(View.GONE);
            		}
            		update.setVisibility(View.GONE);
            	}
                break;
        }
	}
	
	private void setTextViewSingleLine(TextView textView){
		textView.setSingleLine(true);
		textView.setEllipsize(TextUtils.TruncateAt.END);
	}
	
	private void setTextView2Line(TextView textView){
		textView.setSingleLine(false);
		textView.setMaxLines(2);
	}

}
